package com.yingpai.fitness.dvp_2_0.main.activity.fitness;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.main.bean.pay.ChongZhiDingDanEntiy;
import com.yingpai.fitness.dvp_2_0.main.bean.pay.ZfbChongZhiEntity;
import com.yingpai.fitness.dvp_2_0.main.util.PayUtil;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.callback.WechatCallBack;
import com.yingpai.fitness.dvp_2_0.main.util.WechatLoginUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.store.CourseDetailBean;
import com.yingpai.fitness.entity.store.CreateOrderIdBean;
import com.yingpai.fitness.entity.store.PersonalDetailBean;
import com.yingpai.fitness.entity.wx.TokenBean;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2018/8/15.
 */

public class SureOrderActivity extends CommonActivity implements PayUtil.codeResultClickInterface, WechatCallBack {

    @BindView(R.id.photo)
    ImageView photo;
    @BindView(R.id.course)
    TextView course;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.timeLl)
    LinearLayout timeLl;
    @BindView(R.id.sum)
    TextView sum;
    @BindView(R.id.sumLl)
    LinearLayout sumLl;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.remarks)
    EditText remarks;
    @BindView(R.id.realPay)
    TextView realPay;
    @BindView(R.id.weChatPayCb)
    CheckBox weChatPayCb;
    @BindView(R.id.aLiPayCb)
    CheckBox aLiPayCb;
    private String tag = "";
    private Dialog dialog;
    private LinearLayout dialog_pay_success;
    private CourseDetailBean.MapData.CurriculumData curriculumData;
    private PersonalDetailBean.MapData.CurriculumData curriculumData1;
    private int courseId;
    private PersonalDetailBean.MapData.CoachData coachData;
    private CreateOrderIdBean mCreateOrderIdBean;
    private TokenBean tokenBean;
    private DecimalFormat df = new DecimalFormat("######.###");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.activity_sure_order);
    }

    @Override
    protected void initView() {
        setTitle("确认订单");

        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String flag = bundle.getString("flag");

            if ("course".equals(flag)) {
                curriculumData = (CourseDetailBean.MapData.CurriculumData) bundle.getSerializable("course");
                courseId = curriculumData.getId();
                Glide.with(this)
                        .load(curriculumData.getCategoryPhotoUrl())
                        .error(R.mipmap.default_big_bg)
                        .into(photo);

                course.setText(curriculumData.getName());
                name.setVisibility(View.INVISIBLE);
                sumLl.setVisibility(View.INVISIBLE);
                time.setText(curriculumData.getStartTime().substring(5) + "~" + curriculumData.getEndTime().substring(curriculumData.getEndTime().indexOf(" ") + 1));
                money.setText("￥" + df.format(curriculumData.getPrice() / 100));
                realPay.setText("￥" + df.format(curriculumData.getPrice() / 100));
            } else {
                curriculumData1 = (PersonalDetailBean.MapData.CurriculumData) bundle.getSerializable("personal");
                coachData = (PersonalDetailBean.MapData.CoachData) bundle.getSerializable("personal_coach");
                courseId = curriculumData1.getId();
                Glide.with(this)
                        .load(coachData.getPhotoUrl())
                        .error(R.mipmap.default_big_bg)
                        .into(photo);

                timeLl.setVisibility(View.INVISIBLE);
                course.setText(curriculumData1.getName());
                name.setText(coachData.getCoachName());
                money.setText("￥" + df.format(curriculumData1.getPrice() / 100));
                realPay.setText("￥" + df.format(curriculumData1.getPrice() / 100));
            }
        }
    }

    @Override
    protected void initData() {

    }

    private void showSuccessDialog() {
        dialog_pay_success = (LinearLayout) View.inflate(this, R.layout.dialog_pay_success, null);
        dialog = new AlertDialog.Builder(this, R.style.NoBackGroundDialog).create();
        dialog.show();
        dialog.setContentView(dialog_pay_success);
    }

    private void showFaileDialog() {
        LinearLayout dialog_pay_faile = (LinearLayout) View.inflate(this, R.layout.dialog_pay_faile, null);
        dialog = new AlertDialog.Builder(this, R.style.NoBackGroundDialog).create();
        dialog.show();
        dialog.setContentView(dialog_pay_faile);
    }

    @Override
    public void ZFBSuccess(String code) {
        dismissDialog();
        HttpParams params = new HttpParams();
        params.put("customerId", tokenBean.getId());
        params.put("orderId", mCreateOrderIdBean.getMap().getOrderId());
        params.put("payMode", Constant.NUM_1);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CURRICULUM_NOTIFY_PAY, params, Url.CURRICULUM_NOTIFY_PAY, new Callback<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse baseResponse) {
                if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    showSuccessDialog();
                } else {
                    showFaileDialog();
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                showFaileDialog();
            }
        });
    }

    @Override
    public void ZFBFail(String code) {
        dismissDialog();
    }

    @Override
    public void ZFBResultQueRen(String code) {

    }

    @Override
    public void callBack(BaseResp baseResp) {
        dismissDialog();
        if(baseResp.errCode != BaseResp.ErrCode.ERR_OK){
            return;
        }
        HttpParams params = new HttpParams();
        params.put("customerId", tokenBean.getId());
        params.put("orderId", mCreateOrderIdBean.getMap().getOrderId());
        params.put("payMode", Constant.NUM_2);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CURRICULUM_NOTIFY_PAY, params, Url.CURRICULUM_NOTIFY_PAY, new Callback<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse baseResponse) {
                if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    showSuccessDialog();
                } else {
                    showFaileDialog();
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                showFaileDialog();
            }
        });
    }

    @Override
    @OnClick({R.id.aLiPayCb, R.id.weChatPayCb, R.id.sure})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.weChatPayCb:
                if (weChatPayCb.isChecked()) {
                    tag = Constant.WECHAT;
                    aLiPayCb.setChecked(false);
                } else {
                    tag = "";
                }
                break;
            case R.id.aLiPayCb:
                if (aLiPayCb.isChecked()) {
                    tag = Constant.ALIPAY;
                    weChatPayCb.setChecked(false);
                } else {
                    tag = "";
                }
                break;
            case R.id.sure:
                if (!tag.equals("")) {
                    showDialog(this, "支付中...");
                    HttpParams params = new HttpParams();
                    params.put("customerId", tokenBean.getId());
                    params.put("curriculumId", courseId);
                    params.put("sl", sum.getText().toString());
                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.BUY_CURRICULUM_CREATE_ORDER, params, Url.BUY_CURRICULUM_CREATE_ORDER, new Callback<CreateOrderIdBean>() {
                        @Override
                        public void onSuccess(CreateOrderIdBean createOrderIdBean) {
                            if (Constant.REQUEST_SUCCESS.equals(createOrderIdBean.getResult())) {
                                mCreateOrderIdBean = createOrderIdBean;
                                if (tag.equals(Constant.WECHAT)) {
                                    HttpParams httpParams = new HttpParams();
                                    httpParams.put("orderId", createOrderIdBean.getMap().getOrderId());
                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CURRICULUM_WECHAT_PAY, httpParams, Url.CURRICULUM_WECHAT_PAY, new Callback<ChongZhiDingDanEntiy>() {
                                        @Override
                                        public void onSuccess(ChongZhiDingDanEntiy chongZhiDingDanEntiy) {
                                            if (chongZhiDingDanEntiy.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                                WechatLoginUtil.getInstance().setWechatCallBack(SureOrderActivity.this);
                                                PayUtil.wxpay(getApplicationContext(), chongZhiDingDanEntiy.getMap().getResponse().getAppid(),
                                                        chongZhiDingDanEntiy.getMap().getResponse().getPartnerid(),
                                                        chongZhiDingDanEntiy.getMap().getResponse().getPrepayid(),
                                                        chongZhiDingDanEntiy.getMap().getResponse().getNoncestr(),
                                                        chongZhiDingDanEntiy.getMap().getResponse().getTimestamp() + "",
                                                        chongZhiDingDanEntiy.getMap().getResponse().getSign());
                                            } else {
                                                showToast(chongZhiDingDanEntiy.getMsg());
                                            }
                                        }

                                        @Override
                                        public void onError(Response<String> response) {
                                            super.onError(response);
                                            dismissDialog();
                                        }
                                    });
                                } else if (tag.equals(Constant.ALIPAY)) {
                                    HttpParams httpParams = new HttpParams();
                                    httpParams.put("orderId", createOrderIdBean.getMap().getOrderId());
                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CURRICULUM_ALI_PAY, httpParams, Url.CURRICULUM_ALI_PAY, new Callback<ZfbChongZhiEntity>() {
                                        @Override
                                        public void onSuccess(ZfbChongZhiEntity zfbChongZhiEntity) {
                                            if (zfbChongZhiEntity.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                                PayUtil.zfbpay(SureOrderActivity.this, SureOrderActivity.this, zfbChongZhiEntity.getMap().getResponse());
                                            } else {
                                                showToast(zfbChongZhiEntity.getMsg() + "");
                                            }
                                        }

                                        @Override
                                        public void onError(Response<String> response) {
                                            super.onError(response);
                                            dismissDialog();
                                        }
                                    });
                                }
                            } else {
                                showToast(createOrderIdBean.getMsg());
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                } else {
                    showToast("请选择支付方式");
                }
                break;
        }
    }

}
